package jsyf.oa.service.thurTrack;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import jsyf.oa.dao.system.*;
import jsyf.oa.dao.weekplan.WeekPlanDao;
import jsyf.oa.entity.system.*;
import jsyf.oa.ientity.IBaseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.thurTrack.ThurTrackDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.dao.wreport.WReportCustomerDao;
import jsyf.oa.entity.thurTrack.ThurTrackEntity;
import jsyf.oa.entity.thurTrack.TrackEntity;
import jsyf.oa.entity.wreport.WReportCustomerEntity;
import jsyf.oa.facade.thurTrack.ThurTrackFacade;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;


/**
 * Created by Maqiuqiu on 2018/8/16.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ThurTrackService implements ThurTrackFacade {
    public static final String WEDNESDAY_YUCE_REMIND = "温馨提示：\n%1s!请于今晚八点前填写完成每周三商机跟踪表！";
    @Autowired
    private ThurTrackDao thurtrackDao;
    @Autowired
    private WReportCustomerDao wReportCustomerDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private CopierDao copierDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private WeekPlanDao weekPlanDao;

    @Override
    public String save(String jsonData) {
        TrackEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), TrackEntity.class);
        Integer rows;
        JSONObject result = new JSONObject();
        WReportCustomerEntity customerEntity = wReportCustomerDao.getByTel(entity.getMain().getCustomerTel());
        if (customerEntity == null) {
            WReportCustomerEntity wReportCustomerEntity = new WReportCustomerEntity();
            wReportCustomerEntity.setName(entity.getMain().getCustomerName());
            wReportCustomerEntity.setTel(entity.getMain().getCustomerTel());
            wReportCustomerEntity.setCreateUserId(entity.getMain().getRegionalManagerId());
            wReportCustomerEntity.setIntentionModel(entity.getMain().getNeedModel());
            wReportCustomerDao.add(wReportCustomerEntity);
            entity.getMain().setCustomerId(wReportCustomerEntity.getId());
        } else {
            customerEntity.setName(entity.getMain().getCustomerName());
            wReportCustomerDao.update(customerEntity);
            entity.getMain().setCustomerId(customerEntity.getId());
        }
        String province = entity.getMain().getProvinceName();
        String city = entity.getMain().getCityName();
        String county = entity.getMain().getCountyName();
        String customerAddress = province + city + county;
        boolean flag = false;
        if ("0".equals(entity.getMain().getId()) || StringUtils.isBlank(entity.getMain().getId())) {

            //获取区域经理信息
            String userId = entity.getMain().getRegionalManagerId();
            List<JSONObject> jsonObject = thurtrackDao.getRegionByUserId(userId);
            if (jsonObject.size() > 0) {
                entity.getMain().setRegionalId(jsonObject.get(0).getString("regionId"));
            }
            //插入的是周三的日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                entity.getMain().setDay(getThursday(sdf.format(new Date())));
            } catch (Exception e) {
                e.printStackTrace();
            }
            entity.getMain().setCustomerAddress(customerAddress);
            rows = thurtrackDao.add(entity.getMain());
        } else {
            ThurTrackEntity thurTrackEntity = (ThurTrackEntity) thurtrackDao.getIBaseEntityById(entity.getMain().getId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                thurTrackEntity.setDay(getThursday(sdf.format(new Date())));
            } catch (Exception e) {
                e.printStackTrace();
            }
            thurTrackEntity.setCurrentAuditId(entity.getMain().getCurrentAuditId());
            thurTrackEntity.setCurrentAuditName(entity.getMain().getCurrentAuditName());
            if (entity.getMain().getAuditFlag().equals(thurTrackEntity.getAuditFlag())) {
                flag = true;
            } else {
                flag = false;
            }
            thurTrackEntity.setAuditFlag(entity.getMain().getAuditFlag());
            thurTrackEntity.setCompanyId(entity.getMain().getCompanyId());
            thurTrackEntity.setCompanyName(entity.getMain().getCompanyName());
            thurTrackEntity.setCustomerAddress(customerAddress);
            thurTrackEntity.setBuildCityName(entity.getMain().getBuildCityName());
            thurTrackEntity.setConfirmationDate(entity.getMain().getConfirmationDate());
            thurTrackEntity.setCloseorderProbability(entity.getMain().getCloseorderProbability());
            thurTrackEntity.setCustomerId(entity.getMain().getCustomerId());
            thurTrackEntity.setCustomerTel(entity.getMain().getCustomerTel());
            thurTrackEntity.setCustomerName(entity.getMain().getCustomerName());
            thurTrackEntity.setYhdeOlder(entity.getMain().getYhdeOlder());
            thurTrackEntity.setHavingModel(entity.getMain().getHavingModel());
            thurTrackEntity.setBuildCondition(entity.getMain().getBuildCondition());
            thurTrackEntity.setNeedModelId(entity.getMain().getNeedModelId());
            thurTrackEntity.setNeedModel(entity.getMain().getNeedModel());
            thurTrackEntity.setNeedNumber(entity.getMain().getNeedNumber());
            thurTrackEntity.setReplacementModel(entity.getMain().getReplacementModel());
            thurTrackEntity.setCompetitorBrand(entity.getMain().getCompetitorBrand());
            thurTrackEntity.setBuyType(entity.getMain().getBuyType());
            thurTrackEntity.setConfirmationStatus(entity.getMain().getConfirmationStatus());
            thurTrackEntity.setDealerquote(entity.getMain().getDealerquote());
            thurTrackEntity.setDealerpolicy(entity.getMain().getDealerpolicy());
            thurTrackEntity.setActualDate(entity.getMain().getActualDate());
            thurTrackEntity.setYujiDeliveryDate(entity.getMain().getYujiDeliveryDate());
            thurTrackEntity.setShijiLoseDate(entity.getMain().getShijiLoseDate());
            thurTrackEntity.setRegionalManagerId(entity.getMain().getRegionalManagerId());
            thurTrackEntity.setRegionalId(entity.getMain().getRegionalId());
            thurTrackEntity.setBigRegionalId(entity.getMain().getBigRegionalId());
            thurTrackEntity.setRegionalManagerName(entity.getMain().getRegionalManagerName());
            thurTrackEntity.setBigRegionalManagerName(entity.getMain().getBigRegionalManagerName());
            thurTrackEntity.setLostorderBrand(entity.getMain().getLostorderBrand());
            thurTrackEntity.setLostorderModel(entity.getMain().getLostorderModel());
            thurTrackEntity.setLostorderFlag(entity.getMain().getLostorderFlag());
            thurTrackEntity.setLostorderReason(entity.getMain().getLostorderReason());
            thurTrackEntity.setLostorderReasonDetails(entity.getMain().getLostorderReasonDetails());
            thurTrackEntity.setSalePrice(entity.getMain().getSalePrice());
            thurTrackEntity.setInterestRate(entity.getMain().getInterestRate());
            thurTrackEntity.setDownPayment(entity.getMain().getDownPayment());
            thurTrackEntity.setReplacementSubsidy(entity.getMain().getReplacementSubsidy());
            thurTrackEntity.setAccessbonus(entity.getMain().getAccessbonus());
            thurTrackEntity.setOtherInformation(entity.getMain().getOtherInformation());
            thurTrackEntity.setInformationIntegrity(entity.getMain().getInformationIntegrity());
            thurTrackEntity.setTransactionProbability(entity.getMain().getTransactionProbability());
            thurTrackEntity.setDeliveryDate(entity.getMain().getDeliveryDate());
            thurTrackEntity.setCreateTime(thurTrackEntity.getCreateTime());
            thurTrackEntity.setProvinceName(entity.getMain().getProvinceName());
            thurTrackEntity.setCityName(entity.getMain().getCityName());
            thurTrackEntity.setCountyName(entity.getMain().getCountyName());
            thurTrackEntity.setUpdateUserId(entity.getMain().getUpdateUserId());
            rows = thurtrackDao.update(thurTrackEntity);
        }
//        //保存审核人信息
//        if ("0".equals(entity.getMain().getId()) || StringUtils.isBlank(entity.getMain().getId())) {
//            //新建-> 直接保存审核人 和抄送人
//            saveAuditorsAndCopier(entity.getMain());
//        } else {
//            //编辑-> 先刪除审核表，重新保存
//            //if (!flag) {
//            delAuditorsAndCopier(entity.getMain().getId());
//            saveAuditorsAndCopier(entity.getMain());
//            //}
//        }
        return rows == 0 ? "" : entity.getMain().getId();
    }

    @Override
    public JSONObject allCommit(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //List<JSONObject> jsonObjectList = new ArrayList<>();
        JSONObject result = new JSONObject();
        String userId = jsonParams.getString("regionalManagerId");
        String selectIds = jsonParams.getString("selectIds");
        String[] arr = selectIds.split(",");
        selectIds = selectIds.replaceAll(",", "','");
        selectIds = "'" + selectIds + "'";
        JSONObject obj = getAuditorsAndCopier(arr[0], userId);
        String userName = "";
        List<IBaseEntity> thurkList =
                thurtrackDao.getIBaseEntityByCondition(" AND ID IN ( " + selectIds + ")  AND REGIONAL_MANAGER_ID = ? ", new Object[]{userId});
        AuditEntity firstAuditor = null;
        for (int i = 0; i < thurkList.size(); i++) {
            ThurTrackEntity entity = (ThurTrackEntity) thurkList.get(i);
            if (i == 0) {
                userName = entity.getRegionalManagerName();
            }
            delAuditorsAndCopier(entity.getId());
            for (int j = 0; j < obj.getJSONArray("auditList").size(); j++) {
                if (j == 0) {
                    firstAuditor = ((AuditEntity) auditDao.convertJson2Entity((obj.getJSONArray("auditList")).getJSONObject(j)));
                }
                AuditEntity auditEntity = ((AuditEntity) auditDao.convertJson2Entity((obj.getJSONArray("auditList")).getJSONObject(j)));
                auditEntity.setMainId(entity.getId());
                auditDao.add(auditEntity);
            }
            for (int j = 0; j < obj.getJSONArray("copierList").size(); j++) {
                CopierEntity copierEntity = (CopierEntity) copierDao.convertJson2Entity((obj.getJSONArray("copierList")).getJSONObject(j));
                copierEntity.setMainId(entity.getId());
                copierDao.add(copierEntity);
            }

            setCurrentAuditor(entity, firstAuditor);

        }

        ArrayList<JSONObject> jsonObjectList = sendMsg("", firstAuditor.getAuditorId(), firstAuditor.getAuditorName(), userId, userName);

        result.put("ids", selectIds);
        result.put("message", jsonObjectList);
        return result;
    }

    @Override
    public JSONObject allAdd(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject result = new JSONObject();
        String userId = jsonParams.getString("createUserId");
        String selectIds = jsonParams.getString("selectIds");
        selectIds = selectIds.replaceAll(",", "','");
        selectIds = "'" + selectIds + "'";
        List<WReportCustomerEntity> customerList = wReportCustomerDao.getEntityListByCondition(
                " AND ID IN ( " + selectIds + ")  AND CREATE_USER_ID = ? ", new Object[]{userId});
        if (customerList.size() > 0) {
//            for (int i = 0; i < customerList.size(); i++) {
//                WReportCustomerEntity entity = customerList.get(i);
//                List<ThurTrackEntity> list =
//                        thurtrackDao.getEntityListByCondition("AND CUSTOMER_TEL = ? ",new Object[]{entity.getTel()});
//                for (int j = 0; j < list.size(); j++) {
//                    ThurTrackEntity thurTrackEntity = list.get(j);
//                    if(thurTrackEntity != null){
//                        wReportCustomerDao.removeByCondition("AND tel = ? ",new String[]{entity.getTel()});
//                    }
//                }
//            }
            thurtrackDao.insertBatch(customerList);
        }
        result.put("ids", selectIds);
        return result;

    }

    //获取一次审核人抄送人信息
    private JSONObject getAuditorsAndCopier(String mainId, String userId) {
        List<AuditEntity> auditList = new ArrayList<>();
        List<CopierEntity> copierList = new ArrayList<>();
        List<JSONObject> regionList =
                userDao.getViewByUserId(" AND id = ?", new Object[]{userId});
        JSONObject regionObj = regionList.get(0);
        //查询[ 大区经理->销售管理经理->销售总监->省总->王转转 ]审核人 -> 保存
        String allParentStr = checkDao.getParentByUserId(userId, true);
        String[] allParentArr = allParentStr.split(",");
        boolean hasDaqu = false;
        boolean hasXiaoShouGuanLi = false;
        boolean hasXiaoShouZongJian = false;
        boolean hasZongJingLi = false;
        boolean hasQuYuZhiChi = false;
        boolean hasQuYuZongJian = false;
        //按主职位查
        for (int i = 0; i < allParentArr.length; i++) {
            List<JSONObject> objectList =
                    userDao.getViewByUserId(" AND id = ? AND main=1 AND jobState !=1",
                            new Object[]{allParentArr[i].substring(1, allParentArr[i].length() - 1)});
            if (objectList != null && objectList.size() > 0) {
                JSONObject jsonObject = objectList.get(0);
                if (jsonObject.getString("roleName").equals("大区经理") && !hasDaqu) {
                    AuditEntity firstAuditor = new AuditEntity();
                    firstAuditor.setAuditorId(jsonObject.getString("id"));
                    firstAuditor.setAuditorName(jsonObject.getString("name"));
                    firstAuditor.setRoleName((jsonObject.getString("roleName")));
                    firstAuditor.setAuditFlag(0);
                    firstAuditor.setAuditSort(0);
                    firstAuditor.setModuleName("thurTrack");
                    firstAuditor.setMainId(mainId);

                    auditList.add(firstAuditor);
                    hasDaqu = true;
                }
                if (jsonObject.getString("roleName").contains("销售管理") && !hasXiaoShouGuanLi) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(jsonObject.getString("id"));
                    copierEntity.setCopierName(jsonObject.getString("name"));
                    copierEntity.setMainId(mainId);
                    copierEntity.setModuleName("thurTrack");
                    copierList.add(copierEntity);
                    hasXiaoShouGuanLi = true;
                }
                if (jsonObject.getString("roleName").equals("总经理") && !hasZongJingLi) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(jsonObject.getString("id"));
                    copierEntity.setCopierName(jsonObject.getString("name"));
                    copierEntity.setMainId(mainId);
                    copierEntity.setModuleName("thurTrack");
                    copierList.add(copierEntity);
                    hasZongJingLi = true;
                }
                if (jsonObject.getString("roleName").equals("区域总监") && !hasQuYuZongJian) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(jsonObject.getString("id"));
                    copierEntity.setCopierName(jsonObject.getString("name"));
                    copierEntity.setMainId(mainId);
                    copierEntity.setModuleName("thurTrack");
                    copierList.add(copierEntity);
                    hasQuYuZongJian = true;
                }
                if (jsonObject.getString("roleName").equals("销售总监") && !hasXiaoShouZongJian) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(jsonObject.getString("id"));
                    copierEntity.setCopierName(jsonObject.getString("name"));
                    copierEntity.setMainId(mainId);
                    copierEntity.setModuleName("thurTrack");
                    copierList.add(copierEntity);
                    hasXiaoShouZongJian = true;
                }
                if (jsonObject.getString("roleName").contains("区域支持") && !hasQuYuZhiChi) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(jsonObject.getString("id"));
                    copierEntity.setCopierName(jsonObject.getString("name"));
                    copierEntity.setMainId(mainId);
                    copierEntity.setModuleName("thurTrack");
                    copierList.add(copierEntity);
                    hasQuYuZhiChi = true;
                }
                if (jsonObject.getString("roleName").equals("集团销售管理")) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(jsonObject.getString("id"));
                    copierEntity.setCopierName(jsonObject.getString("name"));
                    copierEntity.setMainId(mainId);
                    copierEntity.setModuleName("thurTrack");
                    copierList.add(copierEntity);
                }
                if (jsonObject.getString("roleName").equals("后台管理")) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(jsonObject.getString("id"));
                    copierEntity.setCopierName(jsonObject.getString("name"));
                    copierEntity.setMainId(mainId);
                    copierEntity.setModuleName("thurTrack");
                    copierList.add(copierEntity);
                }
                if (jsonObject.getString("roleName").equals("总裁")) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(jsonObject.getString("id"));
                    copierEntity.setCopierName(jsonObject.getString("name"));
                    copierEntity.setMainId(mainId);
                    copierEntity.setModuleName("thurTrack");
                    copierList.add(copierEntity);
                }
            }
        }
        //按兼职位查
        if (hasDaqu && hasXiaoShouGuanLi && hasXiaoShouZongJian && hasZongJingLi) {

        } else {
            for (int i = 0; i < allParentArr.length; i++) {
                List<JSONObject> objectList =
                        userDao.getViewByUserId(" AND id = ? AND main=0 AND jobState !=1",
                                new Object[]{allParentArr[i].substring(1, allParentArr[i].length() - 1)});
                if (objectList != null && objectList.size() > 0) {
                    for (int j = 0; j < objectList.size(); j++) {
                        if (hasDaqu && hasXiaoShouZongJian) {

                        } else {
                            JSONObject jsonObject = objectList.get(j);

                            if (jsonObject.getString("companyId").equals(regionObj.getString("companyId"))) {
                                if (jsonObject.getString("roleName").equals("总经理") && !hasZongJingLi) {
                                    CopierEntity copierEntity = new CopierEntity();
                                    copierEntity.setCopierId(jsonObject.getString("id"));
                                    copierEntity.setCopierName(jsonObject.getString("name"));
                                    copierEntity.setMainId(mainId);
                                    copierEntity.setModuleName("thurTrack");
                                    copierList.add(copierEntity);
                                    hasZongJingLi = true;
                                }
                                if (jsonObject.getString("roleName").contains("区域支持") && !hasQuYuZhiChi) {
                                    CopierEntity copierEntity = new CopierEntity();
                                    copierEntity.setCopierId(jsonObject.getString("id"));
                                    copierEntity.setCopierName(jsonObject.getString("name"));
                                    copierEntity.setMainId(mainId);
                                    copierEntity.setModuleName("thurTrack");
                                    copierList.add(copierEntity);
                                    hasQuYuZhiChi = true;
                                }
                                if (jsonObject.getString("roleName").contains("销售管理") && !hasXiaoShouGuanLi) {
                                    CopierEntity copierEntity = new CopierEntity();
                                    copierEntity.setCopierId(jsonObject.getString("id"));
                                    copierEntity.setCopierName(jsonObject.getString("name"));
                                    copierEntity.setMainId(mainId);
                                    copierEntity.setModuleName("thurTrack");
                                    copierList.add(copierEntity);
                                    hasXiaoShouGuanLi = true;
                                }
                                if (jsonObject.getString("roleName").equals("销售总监") && !hasXiaoShouZongJian) {
                                    CopierEntity copierEntity = new CopierEntity();
                                    copierEntity.setCopierId(jsonObject.getString("id"));
                                    copierEntity.setCopierName(jsonObject.getString("name"));
                                    copierEntity.setMainId(mainId);
                                    copierEntity.setModuleName("thurTrack");
                                    copierList.add(copierEntity);
                                    hasXiaoShouZongJian = true;
                                }
                            }
                            if (jsonObject.getString("departId").equals(regionObj.getString("departId"))) {
                                if (jsonObject.getString("roleName").equals("大区经理") && !hasDaqu) {
                                    AuditEntity firstAuditor = new AuditEntity();
                                    firstAuditor.setAuditorId(jsonObject.getString("id"));
                                    firstAuditor.setAuditorName(jsonObject.getString("name"));
                                    firstAuditor.setRoleName((jsonObject.getString("roleName")));
                                    firstAuditor.setAuditFlag(0);
                                    firstAuditor.setAuditSort(0);
                                    firstAuditor.setMainId(mainId);
                                    firstAuditor.setModuleName("thurTrack");
                                    auditList.add(firstAuditor);
                                    hasDaqu = true;

                                }
                            }
                        }
                    }
                }
            }
        }

        //去除重复的审核人
        List<AuditEntity> tempList = new ArrayList<>();
        String idStr = "";
        for (int i = 0; i < auditList.size(); i++) {
            if (!idStr.contains(auditList.get(i).getAuditorId())) {
                idStr += auditList.get(i).getAuditorId() + ",";
                tempList.add(auditList.get(i));
            }
        }
        auditList = tempList;
        //去除重复的抄送人
        List<CopierEntity> temp2List = new ArrayList<>();
        String id2Str = "";
        for (int i = 0; i < copierList.size(); i++) {
            if (!id2Str.contains(copierList.get(i).getCopierId())) {
                id2Str += copierList.get(i).getCopierId() + ",";
                temp2List.add(copierList.get(i));
            }
        }
        copierList = temp2List;
//        for (int i = 0; i < copierList.size(); i++) {
//            copierDao.add(copierList.get(i));
//        }
        //排序
        Collections.sort(auditList, new Comparator<AuditEntity>() {

            @Override
            public int compare(AuditEntity o1, AuditEntity o2) {
                return o1.getAuditSort().compareTo(o2.getAuditSort());// 按照sortNo升序
            }
        });
//        for (int i = 0; i < auditList.size(); i++) {
//            auditDao.add(auditList.get(i));
//        }
        JSONObject obj = new JSONObject();
        obj.put("auditList", auditList);
        obj.put("copierList", copierList);
        return obj;
    }

    //删除审核人抄送人信息
    private void delAuditorsAndCopier(String mainId) {
        auditDao.removeByCondition(" AND MAIN_ID = ? ", new String[]{mainId});
        copierDao.removeByCondition(" AND MAIN_ID = ? ", new String[]{mainId});
    }

    //更新主表 审核人和审核表的第一审核人////设置当前审核人 setCurrentAuditor(main, auditList.get(0));
    private void setCurrentAuditor(ThurTrackEntity main, AuditEntity currentAuditor) {
        //List<JSONObject> jsonObjectList = new ArrayList<>();
        main.setCurrentAuditId(currentAuditor.getAuditorId());
        main.setCurrentAuditName(currentAuditor.getAuditorName());
        main.setAuditFlag("0");
        currentAuditor.setAuditFlag(0);
        thurtrackDao.update(main);
        auditDao.update(currentAuditor);
    }

    private ArrayList<JSONObject> sendMsg(String mainId, String currentAuditId, String currentAuditName, String userId, String userName) {
        //企业号:给第一审核人发送消息
        JSONObject msgObject = new JSONObject();
        msgObject.put("userIds", currentAuditId);
        //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
        msgObject.put("content", String.format(TRUCK_AUDIT_AUDIT,
                currentAuditName,
                userName,
                DateUtils.parse(new Date(), "yyyy-MM-dd HH:mm")
        ));
        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

        //保存消息到消息表t_sys_message
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setCreateUserId(userId);
        messageEntity.setCreateTime(messageDao.getCurrentTime());
        messageEntity.setContent(String.format(TRUCK_AUDIT_ONE, userName));
        //messageEntity.setContent("每周三商机跟踪");
        messageEntity.setMessageType(1);
        messageEntity.setMainId(mainId);
        messageEntity.setDelFlag(0);
        messageEntity.setOpenUrl("/page/reportForm/salesForecastReport/thursdayTrackList.html");
        messageEntity.setOpenTitle(String.format(TRUCK_AUDIT_ONE, userName));
        messageDao.add(messageEntity);

        //保存第一审核人信息到消息收件人表t_sys_message_receiver
        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
        messageReceiverEntity.setMessageId(messageEntity.getId());
        messageReceiverEntity.setUserId(currentAuditId);
        messageReceiverEntity.setUserType(0);
        messageReceiverEntity.setReadFlag(0);
        messageReceiverDao.add(messageReceiverEntity);

        //发消息
        ArrayList<JSONObject> jsonObjectList = new ArrayList<>();
        jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
        return jsonObjectList;
    }

    @Override
    public JSONObject getTrackById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject results = new JSONObject();
        String id = jsonParams.getString("id");
        JSONObject result = thurtrackDao.getJSONById(id);
        //result.remove("updateTime");
        //result.remove("createTime");
        List<JSONObject> auditList =
                auditDao.getJSONListByCondition(" and MAIN_ID = ? ORDER BY AUDIT_SORT", new Object[]{id});
        List<JSONObject> copierList =
                copierDao.getJSONListByCondition(" and MAIN_ID = ?", new Object[]{id});
        List<JSONObject> historys =
                auditHistoryDao.getJSONListByCondition(" AND MAIN_ID = ? AND AUDIT_FLAG=2 ORDER BY AUDIT_TIME DESC", new Object[]{id});
        results.put("main", result);
        results.put("auditList", auditList);
        results.put("copierList", copierList);
        results.put("auditHistorys", historys);
        return results;
    }

    @Override
    public JSONObject getTrackDetail(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String tel = jsonParams.getString("customerTel");
        String userId = jsonParams.getString("regionalManagerId");
        JSONObject result = thurtrackDao.getTrackDetail(tel, userId);
        return result;
    }

    @Override
    public JSONObject getThurTrackList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String companyId = jsonParams.getString("companyId");
        String regionalManagerId = jsonParams.getString("regionalManagerId");
        String regionalManagerName = jsonParams.getString("regionalManagerName");
        String regionalId = jsonParams.getString("regionalId");
        String bigRegionalId = jsonParams.getString("bigRegionalId");
        String createTime = jsonParams.getString("createTime");
        String customerName = jsonParams.getString("customerName");
        String auditFlag = jsonParams.getString("auditFlag");
        String key = jsonParams.getString("key");
        String dateTime = jsonParams.getString("dateTime");

        String needModel = jsonParams.getString("modelName");
        String day = jsonParams.getString("day");
        String deliveryDate = jsonParams.getString("deliveryDate");
        String type = jsonParams.getString("type");//1:实际销售 2：销售预测

        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        //传参
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();

        if (!StringUtils.isEmpty(needModel)) {
            condition.append(" AND t_rpt_thursday_genzong.NEED_MODEL = '" + needModel + "' ");
        }
        if (!StringUtils.isEmpty(day)) {
            condition.append(" AND t_rpt_thursday_genzong.DAY = '" + day + "' ");
        }
        if (!StringUtils.isEmpty(deliveryDate)) {
            deliveryDate = deliveryDate.substring(0, 4) + "年" + deliveryDate.substring(5, deliveryDate.length()) + "月";
            condition.append(" AND t_rpt_thursday_genzong.DELIVERY_DATE like '" + deliveryDate + "%' ");
        }
        if (!StringUtils.isEmpty(type)) {
            if (type.equals("1")) {
                condition.append(" AND CONFIRMATION_STATUS LIKE ('%已交车%')\n");
                condition.append("AND AUDIT_FLAG=1\n");
            } else {
                condition.append(" AND CONFIRMATION_STATUS  NOT LIKE ('%已交车%')\n" +
                        " AND CONFIRMATION_STATUS  NOT LIKE ('%丢单%')\n");
                condition.append("AND AUDIT_FLAG=1\n");
            }
        }

        if (!StringUtils.isEmpty(companyId) && !companyId.equals("201712161613432EAF27DBCCB7D0E6CA")) {
            condition.append(" AND t_rpt_thursday_genzong.COMPANY_ID = '" + companyId + "' ");
        }
        if (!StringUtils.isEmpty(regionalId)) {
            condition.append(" AND t_rpt_thursday_genzong.REGIONAL_ID = '" + regionalId + "' ");
        }
        if (!StringUtils.isEmpty(auditFlag)) {
            condition.append(" AND t_rpt_thursday_genzong.AUDIT_FLAG = '" + auditFlag + "' ");
        }
        if (!StringUtils.isEmpty(createTime)) {
            condition.append(" AND t_rpt_thursday_genzong.CREATE_TIME LIKE '%" + createTime + "%' ");
        }
        if (!StringUtils.isEmpty(customerName)) {
            condition.append(" AND t_rpt_thursday_genzong.CUSTOMER_NAME = '" + customerName + "' ");
        }
        if (!StringUtils.isEmpty(regionalManagerName)) {
            condition.append(" AND t_rpt_thursday_genzong.REGIONAL_MANAGER_NAME = '" + regionalManagerName + "' ");
        }
        if (!StringUtils.isEmpty(key)) {
            condition.append(" AND (t_rpt_thursday_genzong.REGIONAL_MANAGER_NAME LIKE '%" + key + "%' " +
                    "OR t_rpt_thursday_genzong.CUSTOMER_NAME LIKE '%" + key + "%' ) ");
        }
        if (!StringUtils.isBlank(bigRegionalId)) {
            condition.append(" AND t_rpt_thursday_genzong.BIG_REGIONAL_ID = '" + bigRegionalId + "' ");
        }
        if (!StringUtils.isBlank(dateTime)) {
            try {
                String weekDay = getThursday(dateTime);
                condition.append(" AND t_rpt_thursday_genzong.`DAY`= '" + weekDay + "' ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!StringUtils.isBlank(userId)) {
            condition.append("AND\n" +
                    "(\n" +
                    "REGIONAL_MANAGER_ID = '" + userId + "' \n" +
                    "OR \n" +
                    "(ID IN(SELECT MAIN_ID  FROM t_sys_audit WHERE AUDITOR_ID = '" + userId + "' ) AND AUDIT_FLAG IN( '1','0'))\n" +
                    "OR\n" +
                    "(ID in(SELECT MAIN_ID FROM t_sys_copier WHERE COPIER_ID = '" + userId + "') AND AUDIT_FLAG = '1')\n" +
                    ")");
        }
        condition.append(" ORDER BY sortNo, CREATE_TIME DESC ");
        //查询list
        List<JSONObject> records = thurtrackDao.getThurTrackList(userId, condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        //查询总数
        int recordCount = thurtrackDao.getThurTrackList(userId, condition.toString(), sqlArgs.toArray(), 1, Integer.MAX_VALUE).size();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        //子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public List<JSONObject> getDownList(String userId, String companyId, String bigRegionalId, String regionalManagerId, String key, String date) {
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (!StringUtils.isEmpty(companyId) && !companyId.equals("201712161613432EAF27DBCCB7D0E6CA")) {
            condition.append(" AND t_rpt_thursday_genzong.COMPANY_ID = '" + companyId + "' ");
        }

        if (!StringUtils.isEmpty(bigRegionalId)) {
            condition.append(" AND t_rpt_thursday_genzong.BIG_REGIONAL_ID = '" + bigRegionalId + "' ");
        }
        if (!StringUtils.isEmpty(key)) {
            condition.append(" AND (t_rpt_thursday_genzong.REGIONAL_MANAGER_NAME LIKE '%" + key + "%' " +
                    "OR t_rpt_thursday_genzong.CUSTOMER_NAME LIKE '%" + key + "%' ) ");
        }
        if (!StringUtils.isBlank(date)) {
            try {
                String weekDay = getThursday(date);
                condition.append(" AND t_rpt_thursday_genzong.`DAY`= '" + weekDay + "' ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!StringUtils.isBlank(regionalManagerId) && userId.equals(regionalManagerId)) {
            condition.append(" AND t_rpt_thursday_genzong.REGIONAL_MANAGER_ID = '" + userId + "' ");
        } else if (!StringUtils.isBlank(regionalManagerId) && !userId.equals(regionalManagerId)) {
            condition.append(" AND t_rpt_thursday_genzong.REGIONAL_MANAGER_ID = '" + regionalManagerId + "' AND t_rpt_thursday_genzong.AUDIT_FLAG = '1' ");
        } else {
            condition.append(" AND t_rpt_thursday_genzong.AUDIT_FLAG = '1' ");
        }
        condition.append(" AND t_rpt_thursday_genzong.INFORMATION_INTEGRITY = '100%' ");
        condition.append(" ORDER BY sortNo, CREATE_TIME DESC");
        //查询list
        List<JSONObject> records =
                thurtrackDao.getThurTrackList(userId, condition.toString(), sqlArgs.toArray(), 1, Integer.MAX_VALUE);
        return records;
    }

    @Override
    public JSONObject applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        JSONObject result = new JSONObject();
        String id = jsonPalams.getString("id");
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("userId");//当前审核人ID
        String userName = jsonPalams.getString("userName");//当前审核人NAME
        String roleName = jsonPalams.getString("roleName");//当前审核人ROLENAME
        String advise = jsonPalams.getString("advise");//意见
        UserEntity userEntity = userDao.getById(userId);//获取当前审核人信息
        ThurTrackEntity thurTrackEntity = (ThurTrackEntity) thurtrackDao.getIBaseEntityById(id);
        //添加历史审核记录
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(userEntity.getName());
        auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
        auditHistoryEntity.setAuditType(8);
        auditHistoryDao.add(auditHistoryEntity);
        //更新当前审核人的--审核表记录
        List<AuditEntity> auditEntityList =
                (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition(" and MAIN_ID = ? and AUDITOR_ID = ? ", new Object[]{id, userId});
        if (null != auditEntityList && auditEntityList.size() > 0) {
            AuditEntity auditEntity = auditEntityList.get(0);
            auditEntity.setAuditFlag(Integer.parseInt(auditFlag));
            auditEntity.setAuditAdvise(advise);
            auditEntity.setAuditTime(auditDao.getCurrentTime());
            auditEntity.setAuditorName(userName);
            auditEntity.setRoleName(roleName);
            auditDao.update(auditEntity);
        }
        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        List<AuditEntity> auditList =
                (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition("and MAIN_ID = ?  order by audit_sort", new Object[]{id});
        for (int i = 0; i < auditList.size(); i++) {
            AuditEntity audit = auditList.get(i);
            if (audit.getAuditorId().equals(userId)) {
                //如果是驳回，修改主表状态为驳回->2
                if (auditFlag.equals("2")) {
                    thurTrackEntity.setAuditFlag("2");
                    thurtrackDao.update(thurTrackEntity);

                    //企业号:审核驳回，发消息通知申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", thurTrackEntity.getRegionalManagerId());
                    //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
                    msgObject.put("content", String.format(TRUCK_AUDIT_REJECT,
                            thurTrackEntity.getRegionalManagerName(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //审核驳回，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity messageCreateEntity = new MessageEntity();
                    messageCreateEntity.setCreateUserId(thurTrackEntity.getRegionalManagerId());
                    messageCreateEntity.setCreateTime(thurtrackDao.getCurrentTime());
                    messageCreateEntity.setContent(String.format(TRUCK_AUDIT_REJECT,
                            thurTrackEntity.getRegionalManagerName(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    messageCreateEntity.setMessageType(0);
                    messageCreateEntity.setMainId(id);
                    messageCreateEntity.setDelFlag(0);
                    messageCreateEntity.setOpenUrl("/page/reportForm/salesForecastReport/thursdayTrack.html?id="
                            + thurTrackEntity.getId() + "&pageType=look");
                    messageCreateEntity.setOpenTitle(String.format(TRUCK_AUDIT_THREE,
                            thurTrackEntity.getCustomerName(), audit.getAuditorName()));
                    messageDao.add(messageCreateEntity);

                    //审核驳回，发送消息给申请人,保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageCreateReceiverEntity = new MessageReceiverEntity();
                    messageCreateReceiverEntity.setMessageId(messageCreateEntity.getId());
                    messageCreateReceiverEntity.setUserId(thurTrackEntity.getRegionalManagerId());
                    messageCreateReceiverEntity.setUserType(2);
                    messageCreateReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageCreateReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageCreateEntity, messageCreateReceiverEntity));
                    break;
                }
                //如果是最后一个人审核通过，标记主表状态为通过->1
                if (auditList.size() - 1 == i) {
                    thurTrackEntity.setAuditFlag("1");
                    thurtrackDao.update(thurTrackEntity);

                    //企业号: 最后一个审核通过,发送消息给申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", thurTrackEntity.getRegionalManagerId());
                    //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
                    msgObject.put("content", String.format(TRUCK_AUDIT_PASS,
                            thurTrackEntity.getRegionalManagerName(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //审核通过，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity msgAuditEntity = new MessageEntity();
                    msgAuditEntity.setCreateUserId(thurTrackEntity.getRegionalManagerId());
                    msgAuditEntity.setCreateTime(thurtrackDao.getCurrentTime());
                    msgAuditEntity.setContent(String.format(TRUCK_AUDIT_PASS,
                            thurTrackEntity.getRegionalManagerName(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    msgAuditEntity.setMessageType(0);
                    msgAuditEntity.setMainId(id);
                    msgAuditEntity.setDelFlag(0);
                    msgAuditEntity.setOpenUrl("/page/reportForm/salesForecastReport/thursdayTrack.html?id="
                            + thurTrackEntity.getId() + "&pageType=look");
                    msgAuditEntity.setOpenTitle(String.format(TRUCK_AUDIT_TWO, thurTrackEntity.getCustomerName(), audit.getAuditorName()));
                    messageDao.add(msgAuditEntity);

                    //审核通过，发送消息给申请人，保存消息到表t_sys_message_receiver
                    MessageReceiverEntity msgReceiverEntity = new MessageReceiverEntity();
                    msgReceiverEntity.setMessageId(msgAuditEntity.getId());
                    msgReceiverEntity.setUserId(thurTrackEntity.getRegionalManagerId());
                    msgReceiverEntity.setUserType(2);
                    msgReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(msgReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(msgAuditEntity, msgReceiverEntity));
                }
            } else {
                //下一位审核人才进入，修改审核表状态和主表审核人信息
                if (audit.getAuditFlag().toString().equals("-1")) {
                    audit.setAuditFlag(0);
                    auditDao.update(audit);
                    thurTrackEntity.setCurrentAuditName(audit.getAuditorName());
                    thurTrackEntity.setCurrentAuditId(audit.getAuditorId());
                    thurTrackEntity.setAuditFlag(audit.getAuditFlag().toString());
                    thurtrackDao.update(thurTrackEntity);
                    break;
                }
            }
        }
        //发消息
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    /**
     * 将传来日期，得到对应的周四
     *
     * @param date
     * @return
     * @throws Exception
     */
    private String getThursday(String date) throws Exception {
        int nowDay = DateUtils.dayForWeek(date);
        if (3 == nowDay) {
            return date;
        } else {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(format.parse(date));
            c.add(Calendar.DATE, 3 - nowDay);
            return format.format(c.getTime());
        }
    }

    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }

    public void yuCeRemind() {
        List<JSONObject> regionManagerList =
                userDao.getViewJSONListByCondition(" AND roleName = '区域经理' AND jobState != 1 ", new Object[]{});
        for (int i = 0; i < regionManagerList.size(); i++) {
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", regionManagerList.get(i).getString("id"));
            msgObject.put("content", String.format(WEDNESDAY_YUCE_REMIND, regionManagerList.get(i).getString("name")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
    }

    @Override
    public Boolean getAllThurTrackList() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String preWeekWed = getThursday(DateUtils.getBeforeWeek(date));
            StringBuffer condition = new StringBuffer();
            if(!StringUtils.isBlank(preWeekWed)){
                condition.append(" AND `DAY` = '"+preWeekWed+"' ");
            }
            //List<ThurTrackEntity> thurTruckList = thurtrackDao.getAllThurTrackList(condition.toString());
            List<ThurTrackEntity> thurTruckList = thurtrackDao.getEntityListByCondition(condition.toString(),new Object[]{});
            for (int i = 0; i < thurTruckList.size(); i++) {
                ThurTrackEntity entity = thurTruckList.get(i);
                entity.setAuditFlag("-1");
                String dateNowStr = sdf.format(date);
                try {
                    String weekDay = getThursday(dateNowStr);
                    entity.setDay(weekDay);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            thurtrackDao.insertBatchList(thurTruckList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    //查看客户
    @Override
    public List<JSONObject> getNameAndTel(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String key = jsonParams.getString("key");
        String userId = jsonParams.getString("createUserId");
        List<JSONObject> objectList =
                weekPlanDao.getNameAndTel(" AND t_wrt_customer.`NAME` like ? AND t_wrt_customer.CREATE_USER_ID = ?", new Object[]{"%" + key + "%",userId});
        return objectList;
    }

    @Override
    public JSONObject getCurrMonthDeal(String jsonData) {
        return null;
    }

    @Override
    public JSONObject getCurrMonthList(String jsonData) {
        return null;
    }

    @Override
    public JSONObject getAccuracyRate(String jsonData) {
        return null;
    }

}
